'''
# -*- coding:utf-8 -*-
# @Project: DevOps_api
# @Date: 2023/3/15 - 19:22
# @Author: ysg
# @Describe: 

serializers.py
'''
from rest_framework import serializers
from users.models import Ops_user
from utils.Ops_responses import OpsResponse
from rest_framework.exceptions import APIException
from rest_framework_jwt.settings import api_settings
from django.conf import settings
from utils.Ops_logger import logger

class LoginModelSerializer(serializers.ModelSerializer):
    '''
    用户登录的序列化类
    '''
    username = serializers.CharField()

    class Meta:
        model = Ops_user
        fields = ['username', 'password']

    def _get_user(self, attrs):
        try:
            username = attrs.get('username')
            password = attrs.get('password')
            user = Ops_user.objects.get(username=username)
            if user and user.check_password(password):
                return user
        except:
            raise APIException('用户或密码错误不存在')

    def _get_token(self, user):
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        new_payload = jwt_payload_handler(user)
        token = jwt_encode_handler(new_payload)
        return token

    def validate(self, attrs):
        '''
        验证登录成功与否的全局钩子
        :param attrs:
        :return:
        '''
        # 验证账号密码是否正确
        user = self._get_user(attrs)
        # 生成 token
        token = self._get_token(user)
        # 返回数据
        self.context['username'] = str(user.username)
        self.context['username_id'] = str(user.pk)
        self.context['token'] = token
        self.context['icon'] = settings.MEDIA_ROOT + str(user.icon)
        return attrs
